<template>
  <a-card :bordered="false">
    <detail-list title="基本信息">
      <detail-list-item term="代理名称">{{ agentInfo.name }}</detail-list-item>
      <detail-list-item term="手机号">{{ agentInfo.phone }}</detail-list-item>
      <detail-list-item term="代理等级">{{ levelMap[agentInfo.level] && levelMap[agentInfo.level].text }}
        <a-button type="link" @click="state.showPromotionRecord = true">晋升记录</a-button>
        <a-modal
          maskClosable
          title="晋升记录"
          :visible="state.showPromotionRecord"
          @ok="state.showPromotionRecord = false"
          @cancel="state.showPromotionRecord = false"
        >
          <a-table
            :pagination="false"
            :columns="promotionRecordColumns"
            :data-source="agentInfo.promoted"
          >

          </a-table>
        </a-modal>
      </detail-list-item>
      <detail-list-item term="代理标签">
        <a-tag v-for="(tag, index) in agentInfo.labels" :key="index">{{ tag.name }}</a-tag>
      </detail-list-item>
      <detail-list-item term="代理姓名">{{ agentInfo.real_name }}</detail-list-item>
      <detail-list-item term="代理性别">{{ { 1: '男', 2: '女' }[agentInfo.gender] }}</detail-list-item>
      <detail-list-item term="微信">{{ agentInfo.wechat_number }}</detail-list-item>
      <detail-list-item term="代理生日">{{ agentInfo.birthday }}</detail-list-item>
      <detail-list-item term="归属地">{{ attribution }}</detail-list-item>
      <detail-list-item term="收货地址">{{ agentInfo.address }}</detail-list-item>
    </detail-list>

    <a-divider/>

    <detail-list title="业绩信息">
      <detail-list-item term="可提现金额">
        {{ agentInfo.balance | formatAmount }}
        <a-button type="link" @click="readyAdjustBalance('balance')">调整余额</a-button>
      </detail-list-item>
      <detail-list-item term="不可提现金额">
        {{ agentInfo.unextractable_balance | formatAmount }}
        <a-button type="link" @click="readyAdjustBalance('unextractable_balance')">调整余额</a-button>
        <a-modal
          :title="state.currentAdjustBalanceType === 'balance' ? '修改余额' : '修改不可提现余额'"
          :confirm-loading="state.adjustBalanceConfirmLoading"
          :visible="state.showAdjustBalanceModal"
          @ok="handleAdjustBalance"
          @cancel="state.showAdjustBalanceModal = false"
        >
          <a-form ref="form" :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
            <a-form-item label="当前余额">
              {{ agentInfo[state.currentAdjustBalanceType] | formatAmount }}
            </a-form-item>

            <a-form-item label="操作">
              <a-radio-group v-decorator="['option_type', { initialValue: 1 }]">
                <a-radio :value="1">
                  增加余额
                </a-radio>
                <a-radio :value="2">
                  减少余额
                </a-radio>
              </a-radio-group>
            </a-form-item>

            <a-form-item
              label="金额"
              :extra="`* 当前操作的是代理商的${state.currentAdjustBalanceType === 'balance' ? '' : '不'}可提现余额，请谨慎操作。`"
            >
              <a-input-number width="100%" :min="0" v-decorator="['amount']"/>
            </a-form-item>
          </a-form>
        </a-modal>
      </detail-list-item>
      <detail-list-item term="个人业绩">{{ agentInfo.personal_performance | formatAmount }}</detail-list-item>
      <detail-list-item term="团队业绩">{{ agentInfo.team_performance | formatAmount }}</detail-list-item>
      <detail-list-item term="个人订单">{{ agentInfo.number_of_personal_order }}</detail-list-item>
      <detail-list-item term="团队订单">{{ agentInfo.number_of_team_order }}</detail-list-item>
      <detail-list-item term="直接邀请人">
        {{ agentInfo.direct_inviter && agentInfo.direct_inviter.name }}

        <a-button type="link" @click="state.showAdjustDirectInviterModal = true">调整直接邀请人</a-button>
        <a-modal
          :confirm-loading="state.adjustDirectInviterConfirmLoading"
          :visible="state.showAdjustDirectInviterModal"
          @ok="handleAdjustDirectInviter"
          @cancel="state.showAdjustDirectInviterModal = false"
        >
          <a-form ref="form" :form="showAdjustDirectInviterForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
            <a-form-item
              label="直接邀请人"
              :extra="`* 当前操作的是调整代理商直接邀请人，包含间接邀请人和所属合伙人，以及该代理的下级代理间接间接邀请人和所属合伙人，请谨慎操作。`"
            >
              <agent-by-phone-selection v-decorator="['agent', { rules: [{ required: true, message: '请选择直接邀请人' }] }]" />
            </a-form-item>
          </a-form>
        </a-modal>
      </detail-list-item>
      <detail-list-item term="间接邀请人">{{ agentInfo.indirect_inviter && agentInfo.indirect_inviter.name }}
      </detail-list-item>
      <detail-list-item term="关联合伙人">{{ agentInfo.affiliated_partner && agentInfo.affiliated_partner.name }}
      </detail-list-item>
      <detail-list-item term="合伙人等级">
        {{ agentInfo.affiliated_partner && agentInfo.affiliated_partner.partner_identity && {1: '有限合伙人', 2:'邀约合伙人'}[agentInfo.affiliated_partner.partner_identity.level] }}
      </detail-list-item>
      <detail-list-item term="直接邀请人数">{{ agentInfo.number_of_direct_inviter }}</detail-list-item>
      <detail-list-item term="间接邀请人数">{{ agentInfo.number_of_indirect_inviter }}</detail-list-item>
    </detail-list>

    <a-divider/>

    <detail-list title="团队信息">
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="直接邀请">
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item label="销售时段">
                    <a-range-picker :allowClear="true" @change="directInvitationPerformanceRangePickerOnChange"/>
                  </a-form-item>
                </a-col>

                <a-col :md="8" :sm="24">
                  <span class="table-page-search-submitButtons">
                    <a-button type="primary" @click="$refs.directInvitationTable.refresh(true)">查询</a-button>
                    <a-button
                      type="primary"
                      @click="handleExport(
                        Object.assign(directInvitationQueryParam, {
                          'agent_id': $route.params.id,
                          'type': 1 // 直接邀请
                        }))"
                      style="margin-left: 8px"
                    >导出</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>

          <s-table
            size="default"
            rowKey="id"
            ref="directInvitationTable"
            :columns="directInvitationColumns"
            :scroll="{ x: 1300 }"
            :data="loadDirectInvitationData"
            showPagination="auto"
          />
        </a-tab-pane>

        <a-tab-pane key="2" tab="间接邀请" force-render>
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item label="销售时段">
                    <a-range-picker :allowClear="true" @change="indirectInvitationPerformanceRangePickerOnChange"/>
                  </a-form-item>
                </a-col>

                <a-col :md="8" :sm="24">
                  <span class="table-page-search-submitButtons">
                    <a-button type="primary" @click="$refs.indirectInvitationTable.refresh(true)">查询</a-button>
                    <a-button
                      type="primary"
                      @click="handleExport(
                        Object.assign(indirectInvitationQueryParam, {
                          'agent_id': $route.params.id,
                          'type': 2 // 间接邀请
                        }))"
                      style="margin-left: 8px"
                    >导出</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>

          <s-table
            size="default"
            rowKey="id"
            ref="indirectInvitationTable"
            :columns="indirectInvitationColumns"
            :scroll="{ x: 1300 }"
            :data="loadIndirectInvitationData"
            showPagination="auto"
          />
        </a-tab-pane>
      </a-tabs>
    </detail-list>
  </a-card>
</template>

<script>
  import DetailList from '@/components/DescriptionList/DescriptionList'
  import { adjustAgentBalance, adjustAgentDirectInviter, getAgentInfo, getAgentTeamList } from '@/api/agent'
  import { mapGetters } from 'vuex'
  import { formatAmount } from '@/utils/util'
  import { STable } from '@/components'
  import AgentByPhoneSelection from '@/components/AgentByPhoneSelection/AgentByPhoneSelection'

  const DetailListItem = DetailList.Item

  export default {
    name: 'Info',
    components: { AgentByPhoneSelection, DetailList, DetailListItem, STable },
    computed: {
      ...mapGetters(['levelMap']),
      attribution () {
        let address = ''
        try {
          address = [this.agentInfo.province, this.agentInfo.city, this.agentInfo.area]
            .reduce((address, curr) => address + curr.name, '')
        } catch (e) {
        }

        return address
      }
    },
    created () {
      this.getAgentInfo()
    },
    data () {
      return {
        agentInfo: {},
        form: this.$form.createForm(this),
        showAdjustDirectInviterForm: this.$form.createForm(this),
        state: {
          showPromotionRecord: false,
          showAdjustBalanceModal: false,
          currentAdjustBalanceType: 'balance',
          adjustBalanceConfirmLoading: false,
          showAdjustDirectInviterModal: false,
          adjustDirectInviterConfirmLoading: false
        },
        promotionRecordColumns: [
          {
            title: '晋升后等级',
            dataIndex: 'after_verification_level',
            key: 'after_verification_level',
            customRender: level => {
              return this.levelMap[level].text
            }
          },
          {
            title: '晋升前等级',
            dataIndex: 'level',
            key: 'level',
            customRender: level => {
              return this.levelMap[level].text
            }
          },
          {
            title: '晋升时个人业绩',
            dataIndex: 'when_verifying_personal_performance',
            key: 'when_verifying_personal_performance',
            customRender: performance => {
              return formatAmount(performance)
            }
          },
          {
            title: '晋升时团队业绩',
            dataIndex: 'when_verifying_team_performance',
            key: 'when_verifying_team_performance',
            customRender: performance => {
              return formatAmount(performance)
            }
          },
          {
            title: '晋升时间',
            dataIndex: 'check_date',
            key: 'check_date'
          }
        ],
        directInvitationColumns: [
          {
            title: '代理名称',
            dataIndex: 'name',
            key: 'name'
          },
          {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone'
          },
          {
            title: '个人业绩',
            dataIndex: 'personal_performance',
            key: 'personal_performance',
            customRender: performance => {
              return formatAmount(performance)
            }
          },
          {
            title: '团队业绩',
            dataIndex: 'team_performance',
            key: 'team_performance',
            customRender: performance => {
              return formatAmount(performance)
            }
          },
          {
            title: '当前等级',
            dataIndex: 'level',
            key: 'level',
            customRender: level => {
              return this.levelMap[level].text
            }
          }
        ],
        directInvitationQueryParam: {},
        loadDirectInvitationData: parameter => {
          parameter = Object.assign(parameter, this.directInvitationQueryParam)
          return getAgentTeamList(Object.assign(parameter, {
            'agent_id': this.$route.params.id,
            'type': 1
          })).then(res => {
            return res
          })
        },
        indirectInvitationColumns: [
          {
            title: '代理名称',
            dataIndex: 'name',
            key: 'name'
          },
          {
            title: '个人业绩',
            dataIndex: 'personal_performance',
            key: 'personal_performance',
            customRender: performance => {
              return formatAmount(performance)
            }
          },
          {
            title: '团队业绩',
            dataIndex: 'team_performance',
            key: 'team_performance',
            customRender: performance => {
              return formatAmount(performance)
            }
          },
          {
            title: '当前等级',
            dataIndex: 'level',
            key: 'level',
            customRender: level => {
              return this.levelMap[level].text
            }
          },
          {
            title: '邀请人',
            dataIndex: 'direct_inviter',
            key: 'direct_inviter',
            customRender: directInviter => {
              return directInviter.name || ''
            }
          },
          {
            title: '加入时间',
            dataIndex: 'created_at',
            key: 'created_at'
          }
        ],
        indirectInvitationQueryParam: {},
        loadIndirectInvitationData: parameter => {
          parameter = Object.assign(parameter, this.indirectInvitationQueryParam)
          return getAgentTeamList(Object.assign(parameter, {
            'agent_id': this.$route.params.id,
            'type': 2
          })).then(res => {
            return res
          })
        }
      }
    },
    methods: {
      handleAdjustBalance () {
        const { form, state } = this
        state.adjustBalanceConfirmLoading = true
        form.validateFields((err, values) => {
          if (!err) {
            values.amount *= 100 // 后端单位分
            if (values.option_type === 2) {
              // 减少的情况, 提交负值
              values.amount *= -1
            }
            adjustAgentBalance(
              Object.assign({
                agent_id: this.$route.params.id,
                balance_type: this.state.currentAdjustBalanceType
              }, values))
              .then(_ => {
                this.getAgentInfo()
                this.$message.success('操作成功!')
              })
              .finally(_ => {
                state.adjustBalanceConfirmLoading = false
                this.state.showAdjustBalanceModal = false
              })
          } else {
            state.adjustBalanceConfirmLoading = false
          }
        })
      },
      readyAdjustBalance (type) {
        this.state.currentAdjustBalanceType = type
        this.state.showAdjustBalanceModal = true
      },
      getAgentInfo () {
        getAgentInfo(this.$route.params.id).then(res => {
          this.agentInfo = res
        })
      },
      directInvitationPerformanceRangePickerOnChange (date, dateString) {
        this.directInvitationQueryParam.performance_range_begin = dateString[0]
        this.directInvitationQueryParam.performance_range_end = dateString[1]
      },
      indirectInvitationPerformanceRangePickerOnChange (date, dateString) {
        this.indirectInvitationQueryParam.performance_range_begin = dateString[0]
        this.indirectInvitationQueryParam.performance_range_end = dateString[1]
      },
      handleExport (cond) {
        getAgentTeamList(Object.assign({ export: true }, cond))
      },
      handleAdjustDirectInviter () {
        const { showAdjustDirectInviterForm, state } = this
        state.adjustDirectInviterConfirmLoading = true

        showAdjustDirectInviterForm.validateFields((err, values) => {
          if (!err) {
            adjustAgentDirectInviter(this.$route.params.id, {
              direct_inviter: values.agent.id
            })
              .then(_ => {
                this.getAgentInfo()
                this.$message.success('操作成功!')
              })
              .finally(_ => {
                state.adjustDirectInviterConfirmLoading = false
                state.showAdjustDirectInviterModal = false
              })
          } else {
            state.adjustDirectInviterConfirmLoading = false
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
